//
//  UserAccountViewModel.swift
//  SinaWeibo
//
//  Created by 周小伟 on 16/8/24.
//  Copyright © 2016年 周小伟. All rights reserved.
//网络请求都放到这个模块

import UIKit
import AFNetworking

class UserAccountViewModel: NSObject {
    
    var account:UserAccount?
    
    //增加用户是否登录属性
    var userLogin:Bool {
        return account?.access_token != nil
    }
    
    var token:String?{
        return account?.access_token
    }
    
    var userName: String?{
        return account?.name
    }
    
    var headURL:NSURL?{
        return NSURL(string: (account?.avatar_large ?? ""))
    }
    
    override init() {
        account = UserAccount.loadAccount()
    }
    
    func loadAccessToken(code:String,finished:(error:NSError?)->()){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        
        NetworkTools.sharedTools.requestJsonDict(.POST, urlString: urlString, parmaters: parameters) { (result, error) in
            if error != nil {
                print("-------------------")
                print(error)
                finished(error:error)
                return
            }
            
            //print(result)
            
            let account = UserAccount(dict: result!)
            self.loadUserInfo(account, finished: finished)
        }
    }
    
    private func loadUserInfo(account:UserAccount,finished:(error:NSError?)->()){
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parmaters = ["access_token":account.access_token!,"uid":account.uid!]
        
        NetworkTools.sharedTools.requestJsonDict(.GET, urlString: urlString, parmaters: parmaters) { (result, error) in
            if error != nil{
                finished(error: error)
                return
            }
            
            account.avatar_large = result!["avatar_large"] as? String
            account.name = result!["name"] as? String
            account.saveAccount()
            finished(error: nil)
        }
    }
}
